package mywebsocket

import (
	"log"
	"net/http"

	"github.com/gin-gonic/gin"
	"github.com/gorilla/websocket"
)

var upgrader = websocket.Upgrader{
	ReadBufferSize:  1024,
	WriteBufferSize: 1024,
	CheckOrigin: func(r *http.Request) bool {
		return true
	},
}

func HandleWebSocket(c *gin.Context) {
	// 从上下文获取Manager实例
	manager := c.MustGet("wsManager").(*Manager)

	// 升级WebSocket连接
	conn, err := upgrader.Upgrade(c.Writer, c.Request, nil)
	if err != nil {
		c.AbortWithStatusJSON(500, gin.H{"error": "WS upgrade failed"})
		return
	}
	defer conn.Close()

	// 注册连接
	manager.Add(conn)
	defer manager.Remove(conn)

	// 设置心跳处理器
	conn.SetPongHandler(func(s string) error {
		// 收到ping
		manager.UpdateActive(conn)
		return nil
	})

	// 消息循环
	for {
		messageType, message, err := conn.ReadMessage()
		log.Println("==>", messageType, string(message), err)
		if err != nil {
			if websocket.IsUnexpectedCloseError(err) {
				c.Error(err).SetType(gin.ErrorTypePrivate)
			}
			break
		}

		// 回写消息
		res := "server: " + string(message)
		if err := conn.WriteMessage(messageType, []byte(res)); err != nil {
			log.Println(err)
			return
		}
	}
}
